import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'

interface TableHeightOptions {
  // 表单区域的类名
  formClass?: string
  // 底部区域的类名
  footerClass?: string
  // 额外需要减去的高度
  extraHeight?: number
  // 是否启用自动计算
  autoResize?: boolean
}

export const useTableHeight = (options: TableHeightOptions = {}) => {
  const {
    formClass = '.form-card',
    footerClass = '.v-footer',
    extraHeight = 208,  // 带分页 208， 不带分页 162， 没按钮 164
    autoResize = true
  } = options

  const tableHeight = ref(0)

  const calculateTableHeight = () => {
    nextTick(() => {
      const windowHeight = window.innerHeight
      const formCard: any = document.querySelector(formClass)
      const formCardHeight = formCard ? formCard.offsetHeight : 0
      const footer: any = document.querySelector(footerClass)
      const footerHeight = footer ? footer.offsetHeight : 0
      tableHeight.value = windowHeight - formCardHeight - footerHeight - extraHeight
    })
  }

  onMounted(() => {
    calculateTableHeight()
    if (autoResize) {
      window.addEventListener('resize', calculateTableHeight)
    }
  })

  onBeforeUnmount(() => {
    if (autoResize) {
      window.removeEventListener('resize', calculateTableHeight)
    }
  })

  return {
    tableHeight,
    calculateTableHeight
  }
}